from django.http import JsonResponse
import json
from ..models import User
from django.core.paginator import Paginator
from django.db.models import Q
from django.contrib.auth.hashers import make_password

def account_handle(request):
    if not request.user.is_authenticated:
        return JsonResponse({'ret': 1, 'msg': '未登录'}, json_dumps_params={'ensure_ascii': False})
    if request.user.usertype not in [1, 1000]:
        return JsonResponse({'ret': 1, 'msg': '非管理员'}, json_dumps_params={'ensure_ascii': False})

    if request.method == 'GET':
        request.params = request.GET
    else:
        request.params = json.loads(request.body)

    action = request.params.get('action')
    if action == 'listbypage':
        return listbypage(request)
    elif action == 'addone':
        return addone(request)
    elif action == 'modifyone':
        return modifyone(request)
    elif action == 'deleteone':
        return deleteone(request)
    else:
        return JsonResponse({'ret': 1, 'msg': '请求错误'}, json_dumps_params={'ensure_ascii': False})


def listbypage(request):
    try:
        qs = User.objects.values(
            'id', 'username', 'realname', 'studentno', 
            'desc', 'usertype').order_by('id')
        pagesize = request.params.get('pagesize')
        pagenum = request.params.get('pagenum')
        keywords = request.params.get('keywords')
        if keywords:
            keywords_list = keywords.split()
            query = Q()
            for k in keywords_list:
                query &= Q(realname__contains=k)
            qs = qs.filter(query)
        pgnt = Paginator(qs, pagesize)
        page = pgnt.get_page(pagenum)
        items = list(page)
        return JsonResponse(
            {
                'ret': 0, 
                'items': items, 
                'total': pgnt.count,
                'keywords': keywords
            }, json_dumps_params={'ensure_ascii': False})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)}, json_dumps_params={'ensure_ascii': False})

def addone(request):
    try:
        data = request.params['data']
        record = User.objects.create(
            realname = data['realname'],
            username = data['username'],
            password = make_password(data['password']),  # 加密
            studentno = data['studentno'],
            desc = data['desc'],
            usertype = data['usertype'],
        )
        return JsonResponse({'ret': 0, 'msg': record.id})
    except Exception as e:
        return JsonResponse(
            {'ret': 1, 'msg': str(e)}, json_dumps_params={'ensure_ascii': False})

def modifyone(request):
    try:
        userid = request.params['id']
        newdata = request.params['newdata']
        user = User.objects.get(id=userid)
        # 先对唯一值字段进行判断
        if 'username' in newdata:
            # 用filter如果找不到会返回空对象
            if User.objects.filter(username=newdata['username']):
                return JsonResponse(
                    {'ret': 1, 'msg': '用户已存在'}, 
                    json_dumps_params={'ensure_ascii': False})
        # 特殊处理密码，通过pop方法
        if 'password' in newdata:
            user.password = make_password(newdata.pop('password'))
        for field, value in newdata.items():
            setattr(user, field, value)
        user.save()
        return JsonResponse({'ret': 0})
    except User.DoesNotExist:
        return JsonResponse({'ret': 1, 'msg': f'id为{userid}的账户不存在'}, 
                            json_dumps_params={'ensure_ascii': False})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)}, json_dumps_params={'ensure_ascii': False})

def deleteone(request):
    try:
        userid = request.params['id']
        user = User.objects.get(id=userid)
        user.delete()
        return JsonResponse({'ret': 0})
    except User.DoesNotExist:
        return JsonResponse({'ret': 1, 'msg': f'id为{userid}的账户不存在'}, 
                            json_dumps_params={'ensure_ascii': False})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)}, json_dumps_params={'ensure_ascii': False})
